//
//  HMMainTabBar.swift
//  大深圳微博01
//
//  Created by shenzhenIOS on 16/4/8.
//  Copyright © 2016年 shenzhenIOS. All rights reserved.
//

import UIKit

class HMMainTabBar: UITabBar {
    
    // 闭包使用流程1.定义闭包属性,传递
    var composeClosure: (() -> ())?

    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 宽度
        let width = self.frame.size.width / CGFloat(HMMainTabBarButtonCount)
        
        // 创建frame
        let newFrame = CGRect(x: 0, y: 0, width: width, height: frame.size.height)
        
        var index = 0
        for subView in subviews {
            //            print("subView: \(subView)")
            // 只想重新设置 UITabBarButton 的 frame
            if subView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                //                subView.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: frame.size.height)
                
                // frame可以平移,CGRectOffset
                subView.frame = CGRectOffset(newFrame, CGFloat(index) * width, 0)
                
                index += index == 1 ? 2 : 1
//                index++
//                if index == 2 {
//                    index++
//                }
            }
        }
        
        // 计算
        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: frame.size.height)
    }
    
    // MARK: - 按钮点击事件
    // @objc: 让OC可以调用我们swift的方法,系统默认会为所有的swift方法加上@objc,如果方法加了private,就不会帮我们加@objc
    @objc private func didClickComposeButton() {
//        print("didClickComposeButton")
        // View 弹不出另外的控制器,点击事件需要告诉外面的控制器
        // 闭包使用流程2.调用闭包
        // 闭包调用流程3.调用别人设置的闭包
        composeClosure?()
    }
    
    // MARK: - 懒加载
    /// 加号按钮
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        
        // 设置
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: Selector("didClickComposeButton"), forControlEvents: UIControlEvents.TouchUpInside)
        
        // 添加按钮到tabBar
        self.addSubview(button)
        
        return button
    }()
}
